package com.ljfiction.book.activitys;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.ljfiction.book.Baner.HisteryReadBean;
import com.ljfiction.book.Dialog.NoBackgLodDialog;
import com.ljfiction.book.MyView.DividerItemDecoration;
import com.ljfiction.book.R;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.tools.ScreenUtils;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.TimeTool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.BaseRequest;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.yanzhenjie.recyclerview.swipe.SwipeItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuBridge;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;
import com.zhy.autolayout.utils.AutoUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class HistoriesReadActivity extends BaseActivity {

    @BindView(R.id.back_history)
    ImageView backHistory;
    @BindView(R.id.recycle_history)
    SwipeMenuRecyclerView recycleHistory;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.noshenma)
    LinearLayout noshenma;
    private BaseQuickAdapter mAdapter;
    private List<HisteryReadBean.DataBean.ListBean> datas = new ArrayList<>();
    private HisteryReadBean history;
    private Intent intent;
    private int page = 1;
    private Context context;
    private NoBackgLodDialog noBackgLodDialog;
    private boolean isfirst=true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_histories_read);
        ButterKnife.bind(this);
        context = this;
        intent = new Intent(this, Reading2Activity.class);
        intView();
        intData();
    }

    private void intData() {
        OkHttpUtils.post(HttpManager.IP + "/person-UserBookReadRecord")

                .params("userid", String.valueOf(UserManageBean.userBean.getUserId()))
                .params("startpage", String.valueOf(page))
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        if (isfirst){
                            if (noBackgLodDialog==null){
                                noBackgLodDialog=new NoBackgLodDialog(HistoriesReadActivity.this,true);
                            }
                            noBackgLodDialog.show();
                        }

                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (isfirst){
                            noBackgLodDialog.dismis();
                            isfirst=false;
                        }
                        refreshLayout.finishRefresh();
                        refreshLayout.finishLoadMore();
                        Gson gs = new Gson();
                        try {
                            history = gs.fromJson(s, HisteryReadBean.class);
                            if (history.getReturnCode() == 200) {
                                datas.addAll(history.getData().getList());
                                }
                            if (datas.size() < 1) {
                                noshenma.setVisibility(View.VISIBLE);
                            }else {
                                noshenma.setVisibility(View.GONE);
                                mAdapter.notifyDataSetChanged();
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });
    }

    private void intView() {
        // 设置菜单创建器。
        recycleHistory.setSwipeMenuCreator(swipeMenuCreator);
        recycleHistory.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recycleHistory.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        recycleHistory.setAdapter(mAdapter = new BaseQuickAdapter<HisteryReadBean.DataBean.ListBean, BaseViewHolder>(R.layout.historyread_item, datas) {
            @Override
            protected void convert(BaseViewHolder helper, HisteryReadBean.DataBean.ListBean item) {
                AutoUtils.autoSize(helper.itemView);
                helper.setText(R.id.bookname_history, item.getBookName())
                        .setText(R.id.time_history, TimeTool.getTimeByLong(item.getDateTimes()))
                        .setText(R.id.authername_history, "作者 " + item.getWriterName())
                        .setText(R.id.chapter_history, "阅读至 " + item.getChapterName());
            }
        });
       /* mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

            }
        });*/

        recycleHistory.setSwipeItemClickListener(new SwipeItemClickListener() {
            @Override
            public void onItemClick(View itemView, int position) {
                intent.putExtra("bookId", String.valueOf(datas.get(position).getBookId()));
                intent.putExtra("type", 1);
                intent.putExtra("chapterId", Integer.valueOf(datas.get(position).getChapterId()));
                startActivity(intent);
            }
        });
        recycleHistory.setSwipeMenuItemClickListener(new SwipeMenuItemClickListener() {
            @Override
            public void onItemClick(SwipeMenuBridge menuBridge) {
                todelet(menuBridge.getAdapterPosition());

            }
        });

        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                if (history.getData().isIsLastPage()){
                    refreshlayout.finishLoadMore();
                    refreshlayout.setEnableLoadMore(false);
                }else {
                    page++;
                    intData();
                }

            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                datas.clear();
                page = 1;
                refreshlayout.setEnableLoadMore(true);
                intData();
            }
        });
    }

    private void todelet(final int position) {
        OkHttpUtils.post(HttpManager.IP+"/person-delBookReadRecord")

                .params("id",String.valueOf(datas.get(position).getId()))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.getInt("returnCode")==200){
                                datas.remove(position);
                                mAdapter.notifyItemRemoved(position);
                                mAdapter.notifyDataSetChanged();
                                recycleHistory.smoothCloseMenu();
                            }else {
                                showToast(jsonObject.getString("msg"));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * 菜单创建器。在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {

            /*SwipeMenuItem addItem = new SwipeMenuItem(context)
                    .setBackgroundDrawable(R.drawable.selector_green)// 点击的背景。
                    .setImage(R.mipmap.ic_action_add) // 图标。
                    .setWidth(size) // 宽度。
                    .setHeight(size); // 高度。
            swipeLeftMenu.addMenuItem(addItem); // 添加一个按钮到左侧菜单。*/

            SwipeMenuItem deleteItem = new SwipeMenuItem(context)
                    .setBackground(R.drawable.topbar)
                    .setText("删除") // 文字。
                    .setTextColor(Color.WHITE) // 文字颜色。
                    .setTextSize(16) // 文字大小。
                    .setWidth(ScreenUtils.getNum(HistoriesReadActivity.this,60))
                    .setHeight(ScreenUtils.getNum(HistoriesReadActivity.this,70))
                    .setBackgroundColor(Color.parseColor("#f77583"));
            swipeRightMenu.addMenuItem(deleteItem);// 添加一个按钮到右侧侧菜单。


            // 上面的菜单哪边不要菜单就不要添加。
        }
    };

    @OnClick(R.id.back_history)
    public void onViewClicked() {
        goBack();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        page = 1;
        datas.clear();
        isfirst=true;
        intData();
    }
}
